var app = getApp();
const Multipart = require('../resource/js/Multipart.min')
Page(Object.assign({}, {
    data: {
        siteroot: app.siteInfo.siteroot.replace('app/index.php', ''),
        uniacid: app.siteInfo.uniacid,
        inited: false,
        checkedrule: false,
        agentcode: 0,
        sortname: '',
        sort: [],
        current: 0,
        cityid: 0,
        tradeid: 0,
        sorttwo: '',
        sorttwolist: [],
        step: 3,
        photos: {},
        step1Data: {},
        step2Data: {},
        step3Data: {},
        cameraShow: false,
        photoType: ''
    },
    onLoad: function (options) {
        var self = this;
        this.setData({
            step: 3,
            canmeraShow: false
        });
        var zfid = options.zfid ? options.zfid : '';
        var code = options.scene ? options.scene : (options.agentcode ? options.agentcode : '');
        self.setData({
            options: options,
        })

        app.com.auth(function () {
            app.com.http('shopinfo_v1', 'POST', {
                op: 'joininfo',
                zfid: zfid
            }, 0, false, '', '', function (res) {
                if (!res.data.errno && res.data) {

                    self.setData({
                        inited: true,
                        status: res.data.data.status,
                        params: res.data.data.params,
                        sharedata: res.data.data.sharedata,
                        sort: res.data.data.sort,
                        city: res.data.data.city,
                        trade: res.data.data.trade,
                        shopbag: res.data.data.shopbag ? res.data.data.shopbag : [],
                        agentcode: code
                    });

                } else {
                    app.com.alert(res.data.message, function () {
                        app.com.backPage(zfid);
                    });
                }
            });
        });
    },
    onShareAppMessage: function () {
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl: self.data.sharedata.img,
        }
    },
    onPullDownRefresh: function () {
        // this.onLoad( this.data.options );
        wx.stopPullDownRefresh();
    },
    address() {
        var self = this;
        wx.chooseLocation({
            success: function (res) {
                self.setData({
                    lat: res.latitude,
                    lng: res.longitude,
                    address: res.address,
                });
            }
        });
    },
    saveStep1Data(e) {
        const {
            detail
        } = e, {
            data
        } = this;
        var postdata = {
            op: 'join',
            name: detail.value.name,
            shopname: detail.value.shopname,
            tel: detail.value.phone,
            pass: detail.value.pass,
            lat: data.lat ? data.lat : 0,
            lng: data.lng ? data.lng : 0,
            address: data.address ? data.address : detail.value.address,
            code: detail.value.code > 0 ? detail.value.code : data.agentcode,
            ctaddress: data.ctaddress ? data.ctaddress : '',
            sortid: data.sortid,
            sorttwo: data.sorttwo,
            cityid: data.cityid,
            tradeid: data.tradeid,
        }

        if (!postdata.name) {
            app.com.toast('请填写姓名');
            return false;
        }
        if (!postdata.tel || !app.com.verify('mobile', postdata.tel)) {
            app.com.toast('请填写电话');
            return false;
        }
        if (!postdata.shopname) {
            app.com.toast('请填写名称');
            return false;
        }
        if (!postdata.pass) {
            app.com.toast('请填写登录密码');
            return false;
        }
        if (postdata.pass.length < 6 || postdata.pass.length > 32) {
            app.com.toast('登录密码在6-32位字符之间');
            return false;
        }
        if (!postdata.lat) {
            app.com.toast('请选择位置');
            return false;
        }
        if (!postdata.address) {
            app.com.toast('请填写地址');
            return false;
        }
        if (!data.checkedrule) {
            app.com.toast('请先同意商户协议');
            return false;
        }
        data.step1Data = {
            ...postdata
        }
        return true
    },
    saveStep2Data(e) {
        let {
            data
        } = this
        var postdata = {
            bagid: data.shopbag && data.shopbag.length > 0 ? data.shopbag[data.current].id : 0,
        }

        if (!postdata.bagid) {
            app.com.toast('请选择套餐');
            return false;
        }
        data.step2Data = {
            ...postdata
        }
        return true
    },
    saveStep3Data(e) {
        const {
            photos
        } = this.data
        if (!photos.shangjia_1) {
            app.com.toast('请拍摄商家门头照');
            return false;
        }
        if (!photos.yingye_1) {
            app.com.toast('请拍摄营业执照正反面');
            return false;
        }
        if (!photos.faren_1 || !photos.faren_2) {
            app.com.toast('请拍摄法人身份证正反面');
            return false;
        }
        if (!photos.hezuo) {
            app.com.toast('请拍摄合作承诺书正面');
            return false;
        }
        this.data.step3Data = {
            ...photos
        }
        return true
    },
    postAllData() {
        const {
            step1Data,
            step2Data,
            step3Data
        } = this.data;
        const postData = {
            ...step1Data,
            ...step2Data
        }
        // const fields = Object.keys(postData).map(key => ({
        //     name: key,
        //     value: postData[key]
        // }))
        const fields = {}
        fields.shopId = app.util.getUrlParam(url, 'shopId')
        fields.from_scene = app.globalData.scene
        const files = Object.keys(step3Data).map(key => ({
            name: key,
            filePath: step3Data[key].path,
            fileData: step3Data[key].file
        }))
        let url = app.com.murl('shopinfo') + '&m=zofui_sales'
        if (url.indexOf('http://') == -1 && url.indexOf('https://') == -1) {
            url = app.util.url(url);
        }
        let sessionid = wx.getStorageSync('userInfo').sessionid;
        let state = app.util.getUrlParam(url, 'state');
        if (!state && sessionid) {
            url = url + '&state=we7sid-' + sessionid
        }

        new Multipart({
            fields,
            files
        }).submit(url).then(res => {
            app.com.alert(res.data.message, () => {
                wx.switchTab({
                    url: '/zofui_sales/pages/index/index'
                });
            });
        });
    },
    submit(e) {
        if (this.data.step === 1) {
            if (this.saveStep1Data(e)) {
                this.setData({
                    step: 2
                })
            }
            return;
        } else if (this.data.step == 2) {
            if (this.saveStep2Data(e)) {
                this.setData({
                    step: 3
                })
            }
            return;
        } else {
            // console.log(this.data.step1Data,1)
            // console.log(this.data.step2Data,2)
            // console.log(this.data.step3Data,3)
            // return
            if (this.saveStep3Data(e)) {
                this.postAllData();
            }
            return;
        }
    },
    checkedrule: function () {
        var self = this;
        self.setData({
            checkedrule: !self.data.checkedrule
        })
    },
    bindRegionChange: function (e) {
        var self = this;
        self.setData({
            ctaddress: e.detail.value[0] + ',' + e.detail.value[1] + ',' + e.detail.value[2]
        })
    },
    selectarea() {
        this.selectComponent('#ausarea').show();
    },
    bindsortChange(e) {
        let key = e.detail.value;
        this.setData({
            sortname: this.data.sort[key].name,
            sortid: this.data.sort[key].id,
            sorttwolist: this.data.sort[key].down ? this.data.sort[key].down : [],
            sorttwo: '',
            sorttwoname: '',
        })
    },
    bindsorttwoChange(e) {
        let key = e.detail.value;
        this.setData({
            sorttwo: this.data.sorttwolist[key].id,
            sorttwoname: this.data.sorttwolist[key].name,
        })
    },
    bindctyChange(e) {
        let key = e.detail.value;
        this.setData({
            cityname: this.data.city[key].name,
            cityid: this.data.city[key].pid,
        })
    },
    bindsqChange(e) {
        let key = e.detail.value;
        this.setData({
            tradename: this.data.trade[key].name,
            tradeid: this.data.trade[key].id,
        })
    },
    bindchange(e) {
        this.setData({
            current: e.detail
        })
    },
    location: function (e) {
        app.com.location(e);
    },
    otherapp: function (e) {
        app.com.otherapp(e);
    },
    navigateto: function (e) {
        app.com.navigateto(e);
    },
    redirectto: function (e) {
        app.com.redirectto(e);
    },
    callphone: function (e) {
        app.com.callphone(e);
    },
    showimages: function (e) {
        app.com.showimages(e);
    },
    FormIdsubmit: function (e) {

    },
    // discountTypeChange(e) {
    //     const discountType = e.detail.value;
    //     let obj = {
    //         discountType
    //     }
    //     if(discountType!=='-1') {
    //         obj.discountValue = '';
    //     }
    //     this.setData(obj);
    // },
    openCamera(e) {
        const {
            photoType
        } = e.currentTarget.dataset;
        // this.setData({cameraShow: true, photoType})
        wx.chooseImage({
            count: 1,
            success: res => {
                this.setData({
                    photos: {
                        ...this.data.photos,
                        [photoType]: {
                            path: res.tempFilePaths[0],
                            file: res.tempFiles[0]
                        }
                    }
                })
            }
        })
    },
    closeCamera() {
        this.setData({
            cameraShow: false,
            photoType: ''
        })
    },
    takePhoto(e) {
        const {
            photoType
        } = this.data;
        console.log(photoType);
        const ctx = wx.createCameraContext();
        console.log(ctx)
        ctx.takePhoto({
            quality: 'high',
            success: (res) => {
                console.log('temp photo path:', res.tempImagePath);
                this.setData({
                    photos: {
                        [photoType]: res.tempImagePath
                    }
                })
            },
            fail(err) {
                app.com.toast(err)
            }
        })
    },
    showid() {

        wx.previewImage({
            current: '', // 当前显示图片的http链接
            urls: [this.data.params.image_url] // 需要预览的图片http链接列表
        })
    }
}))